var inquirer = require('inquirer');
const exec = require('child_process').exec;
const chalk = require('chalk');
const Koa = require('koa');
const cors = require('koa2-cors');
const bodyParser = require('koa-bodyparser');
const Mock = require('mockjs');
const app = new Koa();
app.use(bodyParser());
app.use(cors());

/**
 * 判断端口号
 */
function checkPortExist(port) {
    return new Promise((resolve, reject)=>{
        exec(`lsof -i:${port}`, (error,stdout,stderr) => {
            if (stdout) {
                console.log(chalk.red(`\n 当前端口号已被占用：\n ${stdout}`));
                resolve(true)
            }else{
                resolve()
            }
        })
    })
}

/**
 * 主入口
 */
async function main(cmd){
    if(!cmd.port){
        inquirer.prompt([
            {
                type:"input",
                message:"请输入端口号",
                name:'port',
            }
        ]).then(async answers=>{
            handleKoa(answers.port)
        })
    }else{
        handleKoa(cmd.port)
    }
}

async function handleKoa (port){
    const PortExist = await checkPortExist(port);
    if(PortExist) return;
   
    app.use(async ctx => {
        const { request } = ctx;
        let params;
        if (ctx.method === 'GET') {
            params = request.query;
        } else if (ctx.method === 'POST') {
            params = request.body;
        }
        const apiName = request.url.split('?')[0].split(request.header.host).pop().split('.')[0];
        if (apiName) {
            let modulePath = process.cwd()+apiName; //这里不写后缀，可以支持更多格式，顺序为 demo.js > demo.json > demo
            require.cache[modulePath] && delete require.cache[modulePath];
            ctx.response.type = 'application/json';
            try {
                let fileContent = require(modulePath);
                if(typeof fileContent==='function'){
                    ctx.response.body = fileContent(Mock);
                }else{
                    ctx.response.body = Mock.mock(fileContent);
                }
            } catch (error) {
                ctx.response.body = '无此接口';
            }
        }
    });
    app.listen(port);
    console.log(chalk.green(`Mock server started at http://localhost:${port} `));
}
module.exports = main;